<template>
  <div>
    <a-alert message="喵付通" type="info" show-icon style="margin-bottom: 18px">
      <template #description>
        喵付通聚合支付，让支付接口对接前所未有的简单，开通地址：<a
          href="http://ecmpay.cn"
          target="_blank"
          >点我开通</a
        >
      </template>
    </a-alert>
    <a-tabs v-model:activeKey="activeKey" type="card" @change="tabChange">
      <a-tab-pane key="tab1" tab="支付设置">
        <a-form
          ref="formRef"
          :model="typeFormState"
          :rules="typeFormRule"
          :labelCol="labelCol"
          :wrapperCol="wrapperCol"
        >
          <a-form-item label="支付方式" has-feedback required name="pay_type">
            <a-checkbox-group v-model:value="typeFormState.pay_type">
              <a-checkbox value="alipay" name="pay_type"
                ><img
                  src="../../assets/static/img/alipay.png"
                  alt="支付宝"
                  srcset="../../assets/static/img/alipay.png"
                  style="height: 40px"
              /></a-checkbox>
              <a-checkbox
                value="wxpay"
                name="pay_type"
                style="margin-left: 10px; margin-right: 32px"
                ><img
                  src="../../assets/static/img/wxpay.png"
                  alt="微信支付"
                  srcset="../../assets/static/img/wxpay.png"
                  style="height: 40px"
              /></a-checkbox>
            </a-checkbox-group>
          </a-form-item>
          <a-form-item style="margin-left: 12.5%">
            <a-button
              type="primary"
              html-type="submit"
              :loading="typeLoading"
              @click="typeOnSubmit"
            >
              提交
            </a-button>
          </a-form-item>
        </a-form>
      </a-tab-pane>
      <a-tab-pane key="tab2" tab="支付宝支付">
        <a-form
          ref="alipayFormRef"
          :model="alipayFormState"
          :rules="alipayFormRule"
          :labelCol="labelCol"
          :wrapperCol="wrapperCol"
        >
          <div v-if="typeFormState.pay_platform == 'ecmpay'">
            <a-form-item label="喵付通APPId" has-feedback required name="app_id">
              <a-input v-model:value="alipayFormState.app_id" placeholder="请填写应用的APPID" />
            </a-form-item>
            <a-form-item label="喵付通应用私钥" has-feedback required name="app_secret">
              <a-textarea
                v-model:value="alipayFormState.app_secret"
                placeholder="为保障私钥安全，应用私钥一经设置后将不显示，如修改，直接填写后提交即可"
                :rows="4"
              />
            </a-form-item>
            <a-form-item label="授权支付宝应用ID" has-feedback required name="auth_app_id">
              <a-input
                v-model:value="alipayFormState.auth_app_id"
                placeholder="请填写应用的APPID"
              />
            </a-form-item>
            <a-form-item label="异步通知地址" name="notify_url">
              <a-textarea
                v-model:value="alipayFormState.notify_url"
                placeholder="请填写支付结果的异步通知地址，也可在对接支付功能时单独设置"
                :rows="4"
              />
            </a-form-item>
          </div>
          <div v-else>
            <a-form-item label="APPId" has-feedback required name="app_id">
              <a-input
                v-model:value="alipayFormState.app_id"
                placeholder="请填写支付宝应用的APPID"
              />
            </a-form-item>
            <a-form-item label="应用私钥" has-feedback required name="application_private_key">
              <a-textarea
                v-model:value="alipayFormState.application_private_key"
                placeholder="为保障私钥安全，应用私钥一经设置后将不显示，如修改，直接填写后提交即可"
                :rows="4"
              />
            </a-form-item>
            <a-form-item label="接口加签方式" has-feedback required name="type">
              <a-radio-group v-model:value="alipayFormState.type">
                <a-radio :key="1" :value="1">公钥证书方式</a-radio>
                <a-radio :key="2" :value="2">普通公钥方式</a-radio>
              </a-radio-group>
            </a-form-item>
            <a-form-item
              v-show="alipayFormState.type === 2"
              label="支付宝公钥"
              has-feedback
              required
              name="alipay_public_key"
            >
              <a-textarea
                v-model:value="alipayFormState.alipay_public_key"
                placeholder="为保障支付宝公钥安全，支付宝公钥一经设置后将不显示，如修改，直接填写后提交即可"
                :rows="4"
              />
            </a-form-item>
            <a-form-item
              v-show="alipayFormState.type === 1"
              label="应用公钥证书"
              has-feedback
              required
              name="application_cert_path"
            >
              <a-upload
                name="file"
                listType="text"
                :showUploadList="false"
                :action="apiUrl + 'api/common/uploadCrt'"
                :headers="uploadHeaders"
                :beforeUpload="beforeUpload"
                @change="uploadChange"
              >
                <a-tooltip placement="top">
                  <template #title>
                    <span>appCertPublicKey_xxx.crt</span>
                  </template>
                  <a-button
                    v-if="alipayFormState.application_cert_path === ''"
                    style="margin-right: 32px"
                    @click="uploadType('application_cert_path')"
                  >
                    <UploadOutlined /> 上传证书
                  </a-button>
                  <a-button
                    v-else
                    style="margin-right: 32px"
                    @click="uploadType('application_cert_path')"
                  >
                    <PaperClipOutlined /> 已上传
                  </a-button>
                </a-tooltip>
              </a-upload>
              <a-input v-model:value="alipayFormState.application_cert_path" />
            </a-form-item>
            <a-form-item
              v-show="alipayFormState.type === 1"
              label="支付宝公钥证书"
              has-feedback
              required
              name="alipay_cert_path"
            >
              <a-upload
                name="file"
                listType="text"
                :showUploadList="false"
                :action="apiUrl + 'api/common/uploadCrt'"
                :headers="uploadHeaders"
                :beforeUpload="beforeUpload"
                @change="uploadChange"
              >
                <a-tooltip placement="top">
                  <template #title>
                    <span>alipayCertPublicKey_RSA2.crt</span>
                  </template>
                  <a-button
                    v-if="alipayFormState.alipay_cert_path === ''"
                    style="margin-right: 32px"
                    @click="uploadType('alipay_cert_path')"
                  >
                    <UploadOutlined /> 上传证书
                  </a-button>
                  <a-button
                    v-else
                    style="margin-right: 32px"
                    @click="uploadType('alipay_cert_path')"
                  >
                    <PaperClipOutlined /> 已上传
                  </a-button>
                </a-tooltip>
              </a-upload>
              <a-input v-model:value="alipayFormState.alipay_cert_path" />
            </a-form-item>
            <a-form-item
              v-show="alipayFormState.type === 1"
              label="支付宝根证书"
              has-feedback
              required
              name="alipay_root_cert_path"
            >
              <a-upload
                name="file"
                listType="text"
                :showUploadList="false"
                :action="apiUrl + 'api/common/uploadCrt'"
                :headers="uploadHeaders"
                :beforeUpload="beforeUpload"
                @change="uploadChange"
              >
                <a-tooltip placement="top">
                  <template #title>
                    <span>alipayRootCert.crt</span>
                  </template>
                  <a-button
                    v-if="alipayFormState.alipay_root_cert_path === ''"
                    style="margin-right: 32px"
                    @click="uploadType('alipay_root_cert_path')"
                  >
                    <UploadOutlined /> 上传证书
                  </a-button>
                  <a-button
                    v-else
                    style="margin-right: 32px"
                    @click="uploadType('alipay_root_cert_path')"
                  >
                    <PaperClipOutlined /> 已上传
                  </a-button>
                </a-tooltip>
              </a-upload>
              <a-input v-model:value="alipayFormState.alipay_root_cert_path" />
            </a-form-item>
            <a-form-item label="异步通知地址" name="notify_url">
              <a-textarea
                v-model:value="alipayFormState.notify_url"
                placeholder="请填写支付结果的异步通知地址，也可在对接支付功能时单独设置"
                :rows="4"
              />
            </a-form-item>
          </div>
          <a-form-item style="margin-left: 12.5%">
            <a-button
              type="primary"
              html-type="submit"
              :loading="alipayLoading"
              @click="alipayOnSubmit"
            >
              提交
            </a-button>
          </a-form-item>
        </a-form>
      </a-tab-pane>
      <a-tab-pane key="tab3" tab="微信支付">
        <a-form
          ref="wxpayFormRef"
          :model="wxpayFormState"
          :rules="wxpayFormRule"
          :labelCol="labelCol"
          :wrapperCol="wrapperCol"
        >
          <div v-if="typeFormState.pay_platform == 'ecmpay'">
            <a-form-item label="喵付通APPId" has-feedback required name="app_id">
              <a-input v-model:value="wxpayFormState.app_id" placeholder="请填写喵付通APPId" />
            </a-form-item>
            <a-form-item label="商户类别" has-feedback required name="mch_type">
              <a-radio-group v-model:value="wxpayFormState.mch_type">
                <a-radio key="submch" value="submch">喵付通特约商户</a-radio>
                <a-radio key="mch" value="mch">普通商户</a-radio>
              </a-radio-group>
            </a-form-item>
            <a-form-item label="商户号" has-feedback required name="mch_id">
              <a-input v-model:value="wxpayFormState.mch_id" placeholder="请填写商户号" />
            </a-form-item>
            <a-form-item label="喵付通应用私钥" has-feedback required name="app_secret">
              <a-textarea
                v-model:value="wxpayFormState.app_secret"
                placeholder="请填写喵付通应用私钥"
                :rows="4"
              />
            </a-form-item>
            <a-form-item label="异步通知地址" name="notify_url">
              <a-textarea
                v-model:value="wxpayFormState.notify_url"
                placeholder="请填写支付结果的异步通知地址，也可在对接支付功能时单独设置"
                :rows="4"
              />
            </a-form-item>
          </div>
          <div v-else>
            <a-form-item label="应用Id" has-feedback required name="app_id">
              <a-input v-model:value="wxpayFormState.app_id" placeholder="请填写微信应用的APPID" />
            </a-form-item>
            <a-form-item label="商户号" has-feedback required name="mch_id">
              <a-input v-model:value="wxpayFormState.mch_id" placeholder="请填写商户号" />
            </a-form-item>
            <a-form-item label="APIv3密钥" has-feedback required name="api_v3_code">
              <a-textarea
                v-model:value="wxpayFormState.api_v3_code"
                placeholder="请填写APIv3密钥"
                :rows="4"
              />
            </a-form-item>
            <a-form-item label="商户私钥" has-feedback required name="merchant_private_key">
              <a-upload
                name="file"
                listType="text"
                :showUploadList="false"
                :action="apiUrl + 'api/common/uploadCrt'"
                :headers="uploadHeaders"
                :beforeUpload="beforeUpload"
                @change="uploadChange"
              >
                <a-tooltip placement="top">
                  <template #title>
                    <span>apiclient_key.pem</span>
                  </template>
                  <a-button
                    v-if="wxpayFormState.merchant_private_key === ''"
                    style="margin-right: 32px"
                    @click="uploadType('merchant_private_key')"
                  >
                    <UploadOutlined /> 上传证书
                  </a-button>
                  <a-button
                    v-else
                    style="margin-right: 32px"
                    @click="uploadType('merchant_private_key')"
                  >
                    <PaperClipOutlined /> 已上传
                  </a-button>
                </a-tooltip>
              </a-upload>
              <a-input v-model:value="wxpayFormState.merchant_private_key" />
            </a-form-item>
            <a-form-item label="商户证书" has-feedback required name="merchant_certificate">
              <a-upload
                name="file"
                listType="text"
                :showUploadList="false"
                :action="apiUrl + 'api/common/uploadCrt'"
                :headers="uploadHeaders"
                :beforeUpload="beforeUpload"
                @change="uploadChange"
              >
                <a-tooltip placement="top">
                  <template #title>
                    <span>apiclient_cert.pem</span>
                  </template>
                  <a-button
                    v-if="wxpayFormState.merchant_certificate === ''"
                    style="margin-right: 32px"
                    @click="uploadType('merchant_certificate')"
                  >
                    <UploadOutlined /> 上传证书
                  </a-button>
                  <a-button
                    v-else
                    style="margin-right: 32px"
                    @click="uploadType('merchant_certificate')"
                  >
                    <PaperClipOutlined /> 已上传
                  </a-button>
                </a-tooltip>
              </a-upload>
              <a-input v-model:value="wxpayFormState.merchant_certificate" />
            </a-form-item>
            <a-form-item label="异步通知地址" name="notify_url">
              <a-textarea
                v-model:value="wxpayFormState.notify_url"
                placeholder="请填写支付结果的异步通知地址，也可在对接支付功能时单独设置"
                :rows="4"
              />
            </a-form-item>
          </div>
          <a-form-item style="margin-left: 12.5%">
            <a-button
              type="primary"
              html-type="submit"
              :loading="wxpayLoading"
              @click="wxpayOnSubmit"
            >
              提交
            </a-button>
          </a-form-item>
        </a-form>
      </a-tab-pane>
    </a-tabs>
  </div>
</template>

<script lang="ts">
import { IconFont } from '@/components/iconfont'
import { defineComponent, reactive, toRefs, onMounted, ref, toRaw } from 'vue'
import { Row, Col, Upload } from 'ant-design-vue'
import { UploadOutlined, PaperClipOutlined } from '@ant-design/icons-vue'
import { requestSuccess, requestFailed } from '@/utils/feedback'
import { getPaySetting, editPaySetting } from '@/api/system'
import { ACCESS_TOKEN } from '@/store/mutation-types'
import { storage } from '@/utils/Storage'
import { apiUrl } from '@/utils/common'

export default defineComponent({
  name: 'UserList',
  components: {
    IconFont,
    UploadOutlined,
    PaperClipOutlined,
    [Row.name]: Row,
    [Col.name]: Col,
    [Upload.name]: Upload
  },
  setup() {
    const formRef = ref()
    const alipayFormRef = ref()
    const wxpayFormRef = ref()
    const state = reactive({
      typeLoading: false,
      alipayLoading: false,
      wxpayLoading: false,
      uploadHeaders: {},
      activeKey: ref('tab1'),
      apiUrl: apiUrl(),
      imageUrl: '',
      imagePath: '',
      upload_type: '',
      labelCol: {
        xs: { span: 24 },
        sm: { span: 3 }
      },
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 16 }
      }
    })
    function uploadType(type) {
      state.upload_type = type
    }
    const typeFormState = reactive({
      pay_type: [],
      pay_platform: '',
      tab: 'tab1'
    })
    const typeFormRule = {
      pay_type: [{ required: true, message: '请选择支付类型', trigger: ['change'], type: 'array' }],
      tab: [{ required: false }]
    }
    const alipayFormState = reactive({
      app_id: '',
      application_private_key: '',
      alipay_public_key: '',
      application_cert_path: '',
      alipay_cert_path: '',
      alipay_root_cert_path: '',
      notify_url: '',
      app_secret: '',
      auth_app_id: '',
      type: '',
      tab: 'tab2'
    })
    const alipayFormRule = {
      app_id: [
        {
          required: true,
          message: '请填写应用的APPID',
          trigger: ['blur', 'change']
        }
      ],
      application_private_key: [
        {
          required: typeFormState.pay_platform == 'ecmpay' ? false : true,
          message: '请填写应用私钥',
          trigger: ['blur', 'change']
        }
      ],
      alipay_public_key: [
        { required: false, message: '请填写应用私钥', trigger: ['blur', 'change'] }
      ],
      type: [
        {
          required: typeFormState.pay_platform == 'ecmpay' ? false : true,
          message: '请选择接口加签方式',
          trigger: ['change'],
          type: 'number'
        }
      ],
      pay_type: [
        {
          required: typeFormState.pay_platform == 'ecmpay' ? false : true,
          message: '请选择支付类型',
          trigger: ['change'],
          type: 'array'
        }
      ],
      tab: [{ required: false }]
    }
    const wxpayFormState = reactive({
      app_id: '',
      mch_id: '',
      mch_type: '',
      app_secret: '',
      api_v3_code: '',
      merchant_private_key: '',
      merchant_certificate: '',
      notify_url: '',
      tab: 'tab3'
    })
    const wxpayFormRule = {
      app_id: [{ required: true, message: '请填写微信应用的APPID', trigger: ['blur', 'change'] }],
      mch_id: [{ required: true, message: '请填写商户号', trigger: ['blur', 'change'] }],
      mch_type: [
        {
          required: typeFormState.pay_platform == 'ecmpay' ? true : false,
          message: '请选择商户类别',
          trigger: ['blur', 'change']
        }
      ],
      api_v3_code: [
        {
          required: typeFormState.pay_platform == 'ecmpay' ? false : true,
          message: '请填写APIv3密钥',
          trigger: ['blur', 'change']
        }
      ],
      merchant_private_key: [
        {
          required: typeFormState.pay_platform == 'ecmpay' ? false : true,
          message: '请上传商户私钥',
          trigger: ['blur', 'change']
        }
      ],
      merchant_certificate: [
        {
          required: typeFormState.pay_platform == 'ecmpay' ? false : true,
          message: '请上传商户证书',
          trigger: ['blur', 'change']
        }
      ],
      tab: [{ required: false }]
    }
    onMounted(() => {
      getDataList()
    })

    const tabChange = () => {
      getDataList()
    }

    function getDataList() {
      getPaySetting({ tab: state.activeKey }).then((res) => {
        if (state.activeKey == 'tab1') {
          typeFormState.pay_type = res.pay_type
          typeFormState.pay_platform = res.pay_platform
        } else if (state.activeKey == 'tab2') {
          for (let item in res) {
            alipayFormState[item] = res[item]
          }
        } else if (state.activeKey == 'tab3') {
          for (let item in res) {
            wxpayFormState[item] = res[item]
          }
        }
      })
    }
    const typeOnSubmit = () => {
      formRef.value
        .validate()
        .then(() => {
          editPaySetting(toRaw(typeFormState))
            .then((res) => {
              if (res.code === 200) {
                requestSuccess(res)
              } else {
                requestFailed(res)
              }
            })
            .finally(() => {
              state.typeLoading = false
            })
        })
        .catch(() => {
          return false
        })
    }
    const alipayOnSubmit = () => {
      alipayFormRef.value
        .validate()
        .then(() => {
          editPaySetting(toRaw(alipayFormState))
            .then((res) => {
              if (res.code === 200) {
                requestSuccess(res)
              } else {
                requestFailed(res)
              }
            })
            .finally(() => {
              state.alipayLoading = false
            })
        })
        .catch(() => {
          return false
        })
    }
    const wxpayOnSubmit = () => {
      wxpayFormRef.value
        .validate()
        .then(() => {
          editPaySetting(toRaw(wxpayFormState))
            .then((res) => {
              if (res.code === 200) {
                requestSuccess(res)
              } else {
                requestFailed(res)
              }
            })
            .finally(() => {
              state.wxpayLoading = false
            })
        })
        .catch(() => {
          return false
        })
    }
    function uploadChange(info) {
      if (info.file.status === 'uploading') {
        return
      }
      if (info.file.status === 'done') {
        if (state.activeKey == 'tab2') {
          alipayFormState[state.upload_type] = info.file.response.data
        } else if (state.activeKey == 'tab3') {
          alipayFormState[state.upload_type] = info.file.response.data
        }
      }
    }
    function beforeUpload(file) {
      const token = storage.get(ACCESS_TOKEN)
      if (token) {
        state.uploadHeaders['Authorization'] = 'Bearer ' + token + ':' + new Date().getTime() // 让每个请求携带token
      }
      const isCrt = file.type === 'application/x-x509-ca-cert'
      const isPem = file.type === 'application/x-pem-file'
      const isPemE = file.type === ''
      if (!isCrt && !isPem && !isPemE) {
        requestFailed(null, '仅可上传CRT/PEM格式的文件')
        return false
      }
      return isCrt || isPem || isPemE
    }
    return {
      ...toRefs(state),
      beforeUpload,
      uploadChange,
      formRef,
      alipayFormRef,
      alipayFormState,
      alipayFormRule,
      wxpayFormRef,
      wxpayFormState,
      wxpayFormRule,
      typeFormRule,
      typeFormState,
      tabChange,
      typeOnSubmit,
      alipayOnSubmit,
      wxpayOnSubmit,
      uploadType,
      getDataList
    }
  }
})
</script>

<style lang="scss" scoped>
::v-deep(.ant-checkbox) {
  display: none;
}
.ant-checkbox-wrapper.ant-checkbox-wrapper-checked {
  border: 2px solid #1890ff;
  border-radius: 3px;
}
.ant-checkbox-wrapper.ant-checkbox-wrapper-checked:before {
  content: '';
  position: absolute;
  right: 0;
  bottom: 0;
  border: 10px solid #1890ff;
  border-top-color: transparent;
  border-left-color: transparent;
}
.ant-checkbox-wrapper.ant-checkbox-wrapper-checked:after {
  content: '';
  width: 5px;
  height: 11px;
  position: absolute;
  right: 3px;
  bottom: 2px;
  border: 2px solid #fff;
  border-top-color: transparent;
  border-left-color: transparent;
  transform: rotate(45deg);
}
.ant-checkbox-wrapper {
  border: 2px solid #ebebeb;
  border-radius: 3px;
}
</style>
